<?php

namespace Pm\Controllers;

use Admin\Models\pm\XhpmProjectTask;
use Admin\Models\pm\XhpmProjectCount;
use Admin\Models\pm\XhpmTaskMember;
use Admin\Models\pm\XhpmTaskLog;
use Admin\Models\pm\XhpmSchedule;
use Admin\Models\track\XhtrackTask;
use Helpers\Main;
use Helpers\Assets;
use Admin\Models\pm\XhpmProject;
use Modules\Power;
use Helpers\User;
use Admin\Models\sys\XhsysEnum;

class TaskController extends ControllerBase
{
    private static $task_levels = [
        1 => '普通',
        2 => '重要',
        3 => '紧急',
    ];

    private static $task_status = [
        1 => '待处理',
        2 => '进行中',
        3 => '已完成',
        4 => '已关闭',
    ];

    private static $project_status;

    private static $if_xhjsb;

    public function initialize()
    {
        $userInfo = Main::getLoginUserInfo();
        $depTag = $userInfo['depTag'];
        $logonName = $userInfo['logonName'];
        if (in_array('XHJSB', $depTag) || $logonName == 'admin') {
            self::$project_status = [
                1 => '未开始',
                2 => '进行中',
                5 => '已完成',
                3 => '测试中',
                4 => '已发布',
                6 => '已暂停',
            ];
            self::$if_xhjsb = 1;
        } else {
            self::$project_status = [
                1 => '未开始',
                2 => '进行中',
                5 => '已完成',
                6 => '已暂停',
            ];
            self::$if_xhjsb = 0;
        }
    }

    /**
     * 任务列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180418
     */
    public function indexAction()
    {
        if (!Power::exist('Bpm_Project_Task')) {
            return $this->sendViewError('权限不足', '无任务权限');
        }
        //获取项目id
        $iProjectId = $this->request->getQuery('iProjectId', 'int');
        $re = $this->checkTaskListPower($iProjectId);
        if (!$re) {
            return $this->sendViewError('参数错误', '无相关任务');
        }
        $this->view->pick('task/projectTaskList');
        $projectName = XhpmProject::findFirst($iProjectId)->sProjectName;
        $members = $this->modelsManager->createBuilder()
            ->columns("m.iUserId,u.sStaffName")
            ->addFrom('Admin\Models\pm\XhpmProjectMember', 'm')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
            ->where('m.bDelete = 0 AND m.iProjectId = :iProjectId:', array('iProjectId' => $iProjectId))
            ->getQuery()
            ->execute()
            ->toArray();
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/task/taskList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        $this->view->setVars([
            'taskStatus' => self::$task_status,
            'taskLevels' => self::$task_levels,
            'members' => $members,
            'projectId' => $iProjectId,
            'projectName' => $projectName,
            'ifXhjsb' => self::$if_xhjsb,
            'projectStatus' => self::$project_status,
            'projectAdd' => Power::exist('Bpm_Project_Add'),
            'projectEdit' => Power::exist('Bpm_Project_Edit'),
            'projectDel' => Power::exist('Bpm_Project_Del'),
            'projectCheck' => Power::exist('Bpm_Project_Check'),
            'alterProjectStatus' => Power::exist('Bpm_Project_ChangeStatus'),
            'projectTypes' => XhsysEnum::getEnumByNodeName('项目类型'),
            'moduleAdd' => Power::exist('Bpm_Project_Module_Add'),
            'projectTest' => Power::exist('Bpm_ProjectTest'),//项目测试
            'versionAdd' => Power::exist('Bpm_Project_Version_Add'),
            'taskEdit' => Power::exist('Bpm_Project_Task_Edit'),
            'taskAdd' => Power::exist('Bpm_Project_Task_Add'),
            'taskDel' => Power::exist('Bpm_Project_Task_Del'),
        ]);
    }

    /**
     * 获取任务列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180412
     * modify by zqk 20180614
     */
    public function getTaskAction()
    {
        try {
            if (!Power::exist('Bpm_Project_Task')) {
                return $this->sendErrorResponse('500', '权限不足', '无任务权限');
            }
            $status = $this->request->getPost('status', 'int'); //根据任务状态筛选
            $iProjectId = $this->request->getQuery('iProjectId', 'int'); //根据任务状态筛选//项目ID
            $selectProjectId = $this->request->getPost('selectProjectId', 'int'); //根据任务状态筛选//项目ID
            $re = $this->checkTaskListPower($iProjectId);
            if (!$re) {
                return $this->sendErrorResponse(400, '参数错误', '无相关任务');
            }
            $level = $this->request->getPost('level', 'int'); //根据任务等级筛选
            $userId = $this->request->getPost('userid', 'int'); //根据用户id
            $condition = " t.bDelete = 0 AND t.iParentId = 0";
            $condition1 = " bDelete = 0 AND iParentId = :iParentId: ";
            if ($selectProjectId) {
                $condition .= $selectProjectId ? " AND t.iProjectId = $selectProjectId " : '';
                $condition1 .= $selectProjectId ? " AND iProjectId = $selectProjectId " : '';
            } else {
                $condition1 .= $iProjectId ? " AND iProjectId = $iProjectId " : '';
                $condition .= $iProjectId ? " AND t.iProjectId = $iProjectId " : '';
            }
            $condition .= $status && in_array($status, [1, 2, 3, 4]) ? " AND t.iTaskStatus = $status " : "";
            $condition .= $level && in_array($level, [1, 2, 3]) ? " AND t.iLevel = $level " : '';
            if ($userId) {//只查看某个用户负责的任务
                $params = array(
                    'columns' => 'iTaskId',
                    'conditions' => "bIfExecutor=1 AND bDelete=:bDelete: AND iUserId=:iUserId: ",
                    'bind' => array('iUserId' => $userId, 'bDelete' => 0),
                );
                $taskIds = XhpmTaskMember::find($params)->toArray();
                $intaskIds = [];//项目成员条件
                foreach ($taskIds as $k => $taskId) {
                    $intaskIds[] = $taskId['iTaskId'];
                }
                $builder = $this->modelsManager->createBuilder()
                    ->columns("t.sRelatedId,u1.sStaffName as chargeName,u.sStaffName,t.bChecked,t.iTaskId,t.sTaskName,t.dTaskTime,
                        t.iParentId,t.sTaskContent,t.iLevel,t.iTaskStatus,t.iProcess,t.sRemarks,t.tFromAt,t.tEndAt,
                        t.tStartedAt,t.tFinishedAt,t.tCreateDate,t.tLastModifyDate,t.dRealTaskTime")
                    ->addFrom('Admin\Models\pm\XhpmProjectTask', 't')
                    ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=t.iTaskId AND m.bIfExecutor =1 AND m.bDelete = 0', 'm')
                    ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=m1.iTaskId AND m1.bCharge =1 AND m1.bDelete = 0', 'm1')
                    ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
                    ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm1.iUserId = u1.iUserId', 'u1')
                    ->where($condition)
                    ->inwhere('t.iTaskId', $intaskIds)
                    ->orderBy("t.iTaskId desc");
            } else {
                $builder = $this->modelsManager->createBuilder()
                    ->columns("t.sRelatedId,u1.sStaffName as chargeName ,u.sStaffName,t.bChecked,t.iTaskId,t.sTaskName,t.dTaskTime,t.iParentId,
                    t.sTaskContent,t.iLevel,t.iProcess,t.iTaskStatus,t.sRemarks,t.tFromAt,t.tEndAt,t.tStartedAt,
                    t.tFinishedAt,t.tCreateDate,t.tLastModifyDate,t.dRealTaskTime")
                    ->addFrom('Admin\Models\pm\XhpmProjectTask', 't')
                    ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=t.iTaskId AND m.bIfExecutor =1 AND m.bDelete = 0', 'm')
                    ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=m1.iTaskId AND m1.bCharge =1 AND m1.bDelete = 0', 'm1')
                    ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
                    ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm1.iUserId = u1.iUserId', 'u1')
                    ->where($condition)
                    ->orderBy("t.iTaskId desc");
            }
            $data = Main::runBuilderPages($builder, true);
            foreach ($data['rows'] as $key => $value) {
                $parameters = array(
                    'columns' => 'iTaskId',
                    'conditions' => $condition1,
                    'bind' => array('iParentId' => $value['iTaskId']),
                );
                $objs = XhpmProjectTask::find($parameters)->toArray();
                $data['rows'][$key]['state'] = empty($objs) ? '' : "closed";
                $data['rows'][$key]['iconCls'] = empty($objs) ? 'fa fa-file-text' : 'fa fa-folder';
                $children = $this->getTaskChildren($iProjectId, $selectProjectId, $value['iTaskId']);
                $data['rows'][$key]['children'] = $children;
                $relatedIds = explode(',', $data['rows'][$key]['sRelatedId']);
                $expandContent = $this->getExpandDatas($relatedIds);
                $data['rows'][$key]['expandContent'] = $expandContent;
                if ($expandContent) {
                    $data['rows'][$key]['ifExpand'] = 1;
                }
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 获取taskchildren
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180614
     */
    private function getTaskChildren($iProjectId, $selectProjectId, $iTaskId)
    {
        $condition = "t.bDelete=0 AND t.iParentId = :iParentId: ";
        $condition1 = "bDelete=0 AND iParentId = :iParentId: ";
        $param = array('iParentId' => $iTaskId);
        if ($selectProjectId) {
            $condition .= $selectProjectId ? " AND t.iProjectId = $selectProjectId " : '';
            $condition1 .= $selectProjectId ? " AND iProjectId = $selectProjectId " : '';
        } else {
            $condition1 .= $iProjectId ? " AND iProjectId = $iProjectId " : '';
            $condition .= $iProjectId ? " AND t.iProjectId = $iProjectId " : '';
        }
        $data = $this->modelsManager->createBuilder()
            ->columns("t.sRelatedId,u1.sStaffName as chargeName,u.sStaffName,t.bChecked,t.iTaskId,t.sTaskName,t.dTaskTime,
            t.iParentId,t.sTaskContent,t.iProcess,t.iLevel,t.iTaskStatus,t.sRemarks,t.tFromAt,t.tEndAt,
            t.tStartedAt,t.tFinishedAt,t.tCreateDate,t.tLastModifyDate,t.dRealTaskTime")
            ->addFrom('Admin\Models\pm\XhpmProjectTask', 't')
            ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=t.iTaskId AND m.bIfExecutor =1 AND m.bDelete = 0', 'm')
            ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=m1.iTaskId AND m1.bCharge =1 AND m1.bDelete = 0', 'm1')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm1.iUserId = u1.iUserId', 'u1')
            ->where($condition, $param)
            ->orderBy("t.iTaskId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($data as $k => $v) {
            $parameters = array(
                'columns' => 'iTaskId',
                'conditions' => $condition1,
                'bind' => array('iParentId' => $v['iTaskId']),
            );
            $objs = XhpmProjectTask::find($parameters)->toArray();
            if (!empty($objs)) {
                $data[$k]['state'] = "closed";
                $data[$k]['iconCls'] = 'fa fa-folder';
                $data[$k]['children'] = $this->getTaskChildren($iProjectId, $selectProjectId, $v['iTaskId']);
            } else {
                $data[$k]['iconCls'] = 'fa fa-file-text';
            }
            $relatedIds = explode(',', $data[$k]['sRelatedId']);
            $expandContent = $this->getExpandDatas($relatedIds);
            $data[$k]['expandContent'] = $expandContent;
        }
        return $data;
    }

    /**
     * 获取关联任务信息
     *
     * @param $tIds
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180808
     */
    private function getExpandDatas($tIds)
    {
        $datas = $this->modelsManager->createBuilder()
            ->columns("t.sTaskName,t.iTaskStatus,s.sStaffName,t.iProcess")
            ->addFrom('Admin\Models\pm\XhpmProjectTask', 't')
            ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=t.iTaskId AND m.bIfExecutor = 1 AND m.bDelete = 0', 'm')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = s.iUserId', 's')
            ->where("t.bDelete = 0")
            ->inwhere('t.iTaskId', $tIds)
            ->getQuery()
            ->execute()
            ->toArray();
        return $datas;
    }

    /**
     * 新建task表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180418
     */
    public function taskFormAction()
    {
        $iTaskId = $this->request->getQuery('iTaskId', 'int');
        $ifTaskStats = $this->request->getQuery('ifTaskStats', 'int');
        $iProjectId = $this->request->getQuery('iProjectId', 'int');//项目Id
        $selectProjectGrade = $this->request->getQuery('selectProjectGrade', 'int');
        $selectProjectId = $this->request->getQuery('selectProjectId', 'int');
        if (!$ifTaskStats) {
            $ifPower = $this->checkIfNewTask($iProjectId, $selectProjectId, $selectProjectGrade);
            if (!$ifPower) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            if ($selectProjectId) {
                $memberProjectId = $selectProjectId;//获取任务执行与参与人员列表的项目Id
            } else {
                $memberProjectId = $iProjectId;
            }
        }

        if ($iTaskId) {
            if (!Power::exist('Bpm_Project_Task_Edit')) {
                return $this->sendViewError('权限不足', '无编辑任务权限');
            }
            $task = XhpmProjectTask::findFirst([
                'conditions' => "iTaskId = $iTaskId AND bDelete = 0"
            ]);
            $memberProjectId = $task->iProjectId;
            $iProjectId = $task->iProjectId;
        } else {
            if (!Power::exist('Bpm_Project_Task_Add')) {
                return $this->sendViewError('权限不足', '无新增任务权限');
            }
        }
        Assets::easyUI();
        Assets::select2();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/task/taskForm.js');
        $members = $this->modelsManager->createBuilder()
            ->columns("m.iUserId,u.sStaffName")
            ->addFrom('Admin\Models\pm\XhpmProjectMember', 'm')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
            ->where('m.bDelete = 0 AND m.iProjectId = :iProjectId:', array('iProjectId' => $memberProjectId))
            ->getQuery()
            ->execute()
            ->toArray();
        $this->view->setVars([
            'iTaskId' => $iTaskId,
            'ifTaskStats' => $ifTaskStats,
            'iProjectId' => $iProjectId,
            'selectProjectId' => $selectProjectId,
            'selectProjectGrade' => $selectProjectGrade,
            'task_levels' => self::$task_levels,
            'memberProjectId' => $memberProjectId,
            'members' => $members,
        ]);
        $this->view->pick('task/taskForm');
    }

    /**
     * 新建/编辑任务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180418
     */
    public function saveTaskAction()
    {
        $iTaskId = $this->request->getPost('iTaskId', 'int');
        $ifTaskStats = $this->request->getPost('ifTaskStats', 'int');
        $iProjectId = $this->request->getQuery('iProjectId', 'int');//项目Id
        $selectProjectId = $this->request->getPost('selectProjectId', 'int');
        $parentId = $this->request->getPost('iParentId', 'int');
        $bPublic = $this->request->getPost('bPublic', 'int', 0);
        $executorId = $this->request->getPost('executorId');
        $changeUserId = $this->request->getPost('changeUserId');
        $selectProjectGrade = $this->request->getPost('selectProjectGrade', 'int');
        if (!$ifTaskStats) {
            $ifPower = $this->checkIfNewTask($iProjectId, $selectProjectId, $selectProjectGrade);
            if (!$ifPower) {
                return $this->sendErrorResponse(400, '参数错误');
            }
        }
        //任务创建人id  && name
        $userId = Main::getLoginUserInfo('userId');
        $userName = Main::getLoginUserInfo('userName');
        try {
            $this->db->begin();  //开启事务
            if ($parentId) {
                $fatherTask = XhpmProjectTask::findFirst([
                    'columns' => 'iTaskStatus',
                    'conditions' => "bDelete = 0 AND iTaskId = $parentId"
                ]);
                if (in_array($fatherTask->iTaskStatus, [3, 4])) {
                    return $this->sendErrorResponse(500, '父级任务已完成/已关闭');
                }
            }
            if ($iTaskId) {
                if (!Power::exist('Bpm_Project_Task_Edit')) {
                    return $this->sendErrorResponse(500, '权限不足', '无编辑任务权限');
                }
                $task = XhpmProjectTask::findFirst([
                    'conditions' => "iTaskId = $iTaskId AND bDelete = 0"
                ]);
                $creator = XhpmTaskMember::findFirst([
                    'conditions' => "iUserId = $userId AND (bIfCreator = 1 or bIfExecutor = 1 or bCharge = 1)  AND iTaskId = $iTaskId",
                ]);
                if (!$task || (!$creator && !User::isAdmin())) {
                    return $this->sendErrorResponse(500, '编辑任务失败', '无权编辑该任务');
                }
                if ($task->iTaskStatus == 3 || $task->iTaskStatus == 4) {
                    return $this->sendErrorResponse(500, '编辑任务失败', '任务已完成或者已关闭');
                }
            } else {
                if (!Power::exist('Bpm_Project_Task_Add')) {
                    return $this->sendErrorResponse(500, '权限不足', '无任务创建权限');
                }
                $task = new XhpmProjectTask();
                $task->iTaskStatus = 1;                //创建task  初始状态为未处理
                $task->bChecked = 0;
            }
            $task->assign($this->request->getPost());
            if ($selectProjectId) {
                $task->iProjectId = $selectProjectId;
            } else {
                if (!$ifTaskStats) {
                    $task->iProjectId = $iProjectId;
                }
            }
            $task->bPublic = $bPublic;
            $result = $task->save();
            if (!$result) {
                $this->db->rollback();
                return $iTaskId ? $this->sendErrorResponse(500, '编辑任务失败') : $this->sendErrorResponse(500, '创建任务失败');
            }
            //新增任务修改父级任务进度start
            if ($parentId && !$iTaskId) {
                $pre = $this->modifyParentTask($parentId);
                if (!$pre) {
                    $this->db->rollback();
                    return $this->sendErrorResponse('500', '父级任务进度修改失败');
                }
            }
            //新增任务修改父级任务进度end
            //任务成员表添加
            if ($iTaskId) { //如果是编辑先把之前的task用户删除
                $taskmembers = XhpmTaskMember::find([
                    'conditions' => 'bDelete=0 AND iTaskId = :iTaskId:',
                    'bind' => array('iTaskId' => $iTaskId),
                ]);
                foreach ($taskmembers as $taskmember) {
                    if ($taskmember->bIfCreator == 1) {
                        if ($taskmember->iUserId == $executorId) {
                            $taskmember->bIfExecutor = 1;
                        } else {
                            $taskmember->bIfExecutor = 0;
                        }
                        if ($taskmember->iUserId == $changeUserId) {
                            $taskmember->bCharge = 1;
                        } else {
                            $taskmember->bCharge = 0;
                        }
                    } else {
                        $taskmember->bDelete = 1;
                    }

                    $res = $taskmember->save();
                    if (!$res) {
                        $this->db->rollback();
                        return $iTaskId ? $this->sendErrorResponse(500, '编辑任务失败', '任务成员添加失败')
                            : $this->sendErrorResponse(500, '创建任务失败', '任务成员添加失败');
                    }
                }
            }
            $memberIds = $this->request->getPost('memberIds') ? $this->request->getPost('memberIds') : [];
            $taskMemberIds = array_filter(array_unique(array_merge($memberIds, [$executorId, $userId, $changeUserId])));
            $taskMemberIds = array_unique($taskMemberIds);
            foreach ($taskMemberIds as $taskMemberId) {
                //避免重复添加
                $member = XhpmTaskMember::findFirst([
                    'columns' => 'iId',
                    'conditions' => 'bDelete=0  AND iUserId=:iUserId: AND iTaskId = :iTaskId:',
                    'bind' => array('iUserId' => $taskMemberId, 'iTaskId' => $task->iTaskId),
                ]);
                if ($member) {
                    continue;
                }
                $taskMember = new XhpmTaskMember();
                $taskMember->iTaskId = $task->iTaskId;
                $taskMember->iUserId = $taskMemberId;
                if (!$iTaskId) {
                    if ($taskMemberId == $userId) {
                        $taskMember->bIfCreator = 1; //是否是创建者
                    }
                }
                if ($taskMemberId == $executorId) {
                    $taskMember->bIfExecutor = 1;//是否是执行者
                }
                if ($taskMemberId == $changeUserId) {
                    $taskMember->bCharge = 1;//是否是负责人
                }
                $re = $taskMember->save();
                if (!$re) {
                    $this->db->rollback();
                    return $iTaskId ? $this->sendErrorResponse(500, '编辑任务失败', '修改任务成员失败')
                        : $this->sendErrorResponse(500, '创建任务失败', '添加任务成员失败');
                }
            }
            //任务成员表添加end
            //项目统计
            if (!$iTaskId) {//新建任务
                $prore = $this->modifyProjectCount($task->iProjectId, 1);
                if (!$prore) {
                    $this->db->rollback();
                    $this->sendErrorResponse('500', '项目统计失败');
                }
            }
            //判断是否创建日程
            $startdate = $this->request->getPost('tFromAt');
            $enddate = $this->request->getPost('tEndAt');
            if ($iTaskId) {
                $scheduleobj = XhpmSchedule::findFirst([
                    'conditions' => 'bDelete=0 AND iTaskId=:iTaskId:',
                    'bind' => array('iTaskId' => $iTaskId),
                ]);
            }
            if (!$scheduleobj) {
                $scheduleobj = new XhpmSchedule();
            }
            if ($executorId && $startdate && $enddate) {
                $scheduleobj->iUserId = $executorId;
                $scheduleobj->iTaskId = $task->iTaskId;
                $scheduleobj->iProjectId = $task->iProjectId;
                $scheduleobj->sScheduleContent = $task->sTaskContent;
                $scheduleobj->sScheduleName = $task->sTaskName;
                $scheduleobj->iScheduleType = 2;
                $scheduleobj->iScheduleStatus = 1;
                $scheduleobj->tFromAt = $task->tFromAt;
                $scheduleobj->tEndAt = $task->tEndAt;
            } else {
                $scheduleobj->bDelete = 1;
            }
            $ret = $scheduleobj->save();
            if (!$ret) {
                $this->db->rollback();
                return $iTaskId ? $this->sendErrorResponse(500, '编辑任务失败', '日程创建失败')
                    : $this->sendErrorResponse(500, '创建任务失败', '日程创建失败');
            }
            //写入项目日志
            $sContent = $iTaskId ? $userName . '编辑任务' . $task->sTaskName : $userName . '创建任务' . $task->sTaskName;
            $taskLog = new XhpmTaskLog();
            $taskLog->iTaskId = $task->iTaskId;
            $taskLog->sContent = $sContent;
            $r = $taskLog->save();
            if (!$r) {
                $this->db->rollback();
                return $iTaskId ? $this->sendErrorResponse(500, '编辑任务失败') : $this->sendErrorResponse(500, '创建任务失败');
            }
            $this->db->commit();
            return $iTaskId ? $this->sendSuccessResponse('编辑任务成功') : $this->sendSuccessResponse('创建任务成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iTaskId ? $this->sendErrorResponse(500, '编辑任务失败', $exception->getMessage())
                : $this->sendErrorResponse(500, '创建任务失败', $exception->getMessage());
        }
    }

    /**
     * tracttaskList 列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180511
     */
    public function trackTaskListAction()
    {
        if (!Power::exist('Track')) {
            return $this->sendViewError('权限不足');
        }
        $iProjectId = $this->request->getQuery('iProjectId', 'int');//项目Id
        $selectProjectGrade = $this->request->getQuery('selectProjectGrade', 'int');
        $selectProjectId = $this->request->getQuery('selectProjectId', 'int');
        $ifPower = $this->checkIfNewTask($iProjectId, $selectProjectId, $selectProjectGrade);
        if (!$ifPower) {
            return $this->sendViewError('参数错误');
        }
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/task/trackTaskList.js');
        $this->view->setVars([
            'iProjectId' => $iProjectId,
        ]);
        $this->view->pick('task/trackTaskList');
    }

    /**
     * 获取trackTasklist
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180511
     */
    public function getTrackTaskListAction()
    {
        if (!Power::exist('Track')) {
            return $this->sendErrorResponse(500, '权限不足');
        }
        $iTaskType = $this->request->getPost('iTaskType', 'int');//任务类型  1 需求跟踪  2 bug跟踪
        $sTaskName = $this->request->getPost('sTaskName', 'string');
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $selectProjectGrade = $this->request->getPost('selectProjectGrade', 'int');
        $selectProjectId = $this->request->getPost('selectProjectId', 'int');
        $ifPower = $this->checkIfNewTask($iProjectId, $selectProjectId, $selectProjectGrade);
        if (!$ifPower) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        $conditions = 'bDelete = 0 AND (iState = 0 OR iState = 30)';
        $conditions .= $sTaskName ? " AND sTaskName Like '%$sTaskName%'" : '';
        if ($iProjectId) {
            $projectObj = XhpmProject::findFirst([
                'columns' => 'iProductId',
                'conditions' => "iProjectId =$iProjectId AND bDelete = 0"
            ]);
            $conditions .= $projectObj->iProductId ? " AND iProductId = '$projectObj->iProductId'" : '';//项目有指定应用则根据应用筛选track
        }
        $iTTIds = [];
        $tasks = XhpmProjectTask::find([
            'columns' => 'iTTId',
            'conditions' => 'iTTId > 0 AND bDelete = 0 AND iTaskStatus !=4'
        ])->toArray();
        foreach ($tasks as $task) {
            $iTTIds[] = $task['iTTId'];
        }
        if ($iTTIds) {
            if (in_array($iTaskType, [1, 2])) {
                $conditions .= " AND iTaskType=$iTaskType";
                $builder = $this->modelsManager->createBuilder()
                    ->columns("iTTId,sTaskName,sTaskContent")
                    ->From('Admin\Models\track\XhtrackTask')
                    ->where($conditions)
                    ->notInWhere('iTTId', $iTTIds);
            } else {
                //为传递类型
                $builder = $this->modelsManager->createBuilder()
                    ->columns("iTTId,sTaskName,sTaskContent")
                    ->From('Admin\Models\track\XhtrackTask')
                    ->where($conditions)
                    ->inWhere("iTaskType", [1, 2])
                    ->notInWhere('iTTId', $iTTIds);
            }
        } else {
            if (in_array($iTaskType, [1, 2])) {
                $conditions .= " AND iTaskType=$iTaskType";
                $builder = $this->modelsManager->createBuilder()
                    ->columns("iTTId,sTaskName,sTaskContent")
                    ->From('Admin\Models\track\XhtrackTask')
                    ->where($conditions);
            } else {
                //为传递类型
                $builder = $this->modelsManager->createBuilder()
                    ->columns("iTTId,sTaskName,sTaskContent")
                    ->From('Admin\Models\track\XhtrackTask')
                    ->where($conditions)
                    ->inWhere("iTaskType", [1, 2]);
            }
        }
        $datas = Main::runBuilderPaginator($builder, true);
        return $this->sendJsonResponse($datas);
    }

    /**
     * 批量添加任务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180520
     */
    public function addMultiTaskAction()
    {
        if (!Power::exist('Bpm_Project_Task_Add')) {
            return $this->sendErrorResponse(500, '权限不足', '无新增任务权限');
        }
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $selectProjectGrade = $this->request->getPost('selectProjectGrade', 'int');
        $selectProjectId = $this->request->getPost('selectProjectId', 'int');
        $ifPower = $this->checkIfNewTask($iProjectId, $selectProjectId, $selectProjectGrade);
        if (!$ifPower) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        $id = $selectProjectId ? $selectProjectId : $iProjectId;
        $iTTIds = $this->request->getPost('iTTIds');
        //任务创建人id  && name
        $userId = Main::getLoginUserInfo('userId');
        try {
            $project = $id ? XhpmProject::findFirst([
                'columns' => 'iProjectGrade,iParentPid',
                'conditions' => "iProjectId = $id AND bDelete = 0"
            ]) : '';
            if (!$project || !is_array($iTTIds) || empty($iTTIds)) {
                return $this->sendErrorResponse(400, '批量添加失败', '参数错误');
            }
            $trackTasks = $this->modelsManager->createBuilder()
                ->columns('iTTId,sTaskName,sTaskContent,tOfferTime,tPlanFinishTime,mRemarks')
                ->addFrom('Admin\Models\track\XhtrackTask')
                ->where('bDelete = 0')
                ->inWhere("iTTId", $iTTIds)
                ->getQuery()
                ->execute();
            if (!$trackTasks) {
                return $this->sendErrorResponse(400, '批量添加失败', '参数错误');
            }
            $this->db->begin();
            foreach ($trackTasks as $trackTask) {
                $taskObj = new XhpmProjectTask();
                $taskObj->sTaskName = $trackTask->sTaskName;
                $taskObj->sTaskContent = $trackTask->sTaskContent;
                $taskObj->iProjectId = $id;
                $taskObj->iProcess = 0;
                $taskObj->iParentId = 0;
                $taskObj->dTaskTime = 0;
                $taskObj->dRealTaskTime = 0;
                $taskObj->iLevel = 1;
                $taskObj->iTaskType = 2;
                $taskObj->iTTId = $trackTask->iTTId;
                $taskObj->iTaskStatus = 1;
                $taskObj->tFromAt = $trackTask->tOfferTime;
                $taskObj->tEndAt = $trackTask->tPlanFinishTime;
                $taskObj->sRemarks = $trackTask->mRemarks;
                $re = $taskObj->save();
                if (!$re) {
                    $this->db->rollBack();
                    return $this->sendErrorResponse(500, '批量添加任务失败');
                }
                $taskMember = new XhpmTaskMember();
                $taskMember->iUserId = $userId;
                $taskMember->bIfCreator = 1;
                $taskMember->iTaskId = $taskObj->iTaskId;
                $res = $taskMember->save();
                if (!$res) {
                    $this->db->rollBack();
                    return $this->sendErrorResponse(500, '批量添加任务失败', '任务创建人添加失败');
                }
                $fatherProject = XhpmProject::findFirst([
                    'columns' => 'iProjectId',
                    'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                    'bind' => array('iProjectId' => $project->iParentPid),
                ]);
                $grade = $project->iProjectGrade;
                if ($grade == 1) {
                    $projectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $id),
                            'for_update' => true
                        ]
                    );
                    $projectCount->iSumTaskNum = $projectCount->iSumTaskNum + 1;
                    $resu = $projectCount->save();
                } elseif ($grade == 2) {
                    if (!$fatherProject) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(400, '创建任务失败', "无所属项目");
                    }
                    $projectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $id),
                            'for_update' => true
                        ]
                    );
                    $projectCount->iSumTaskNum = $projectCount->iSumTaskNum + 1;
                    $resu = $projectCount->save();
                } elseif ($grade == 3) {
                    if (!$fatherProject) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(400, '创建任务失败', '无所属版本');
                    }
                    $fprojectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $fatherProject->iProjectId),
                            'for_update' => true
                        ]
                    );
                    $fprojectCount->iSumTaskNum = $fprojectCount->iSumTaskNum + 1;
                    $resu1 = $fprojectCount->save();
                    if ($resu1) {
                        $projectCount = XhpmProjectCount::findFirst(
                            [
                                'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                                'bind' => array('iProjectId' => $id),
                                'for_update' => true
                            ]
                        );
                        $projectCount->iSumTaskNum = $projectCount->iSumTaskNum + 1;
                        $resu = $projectCount->save();
                    }
                }
                if (!$resu) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '创建任务失败', '创建任务统计失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('批量添加任务成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '批量添加任务失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的task
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180408
     */
    public function getTaskInfoAction()
    {
        try {
            $iTaskId = $this->request->getPost('iTaskId', 'int');
            if (!$iTaskId) {
                return $this->sendErrorResponse(400, '参数错误', '无相关任务');
            }
            $taskInfo = XhpmProjectTask::findFirst([
                'conditions' => 'bDelete=0 AND iTaskId = :iTaskId:',
                'bind' => array('iTaskId' => $iTaskId),
            ]);
            $executorId = XhpmTaskMember::findFirst([
                'columns' => 'iUserId',
                'conditions' => 'bDelete=0 AND iTaskId = :iTaskId: AND  bIfExecutor =1 ',
                'bind' => array('iTaskId' => $iTaskId),
            ]);
            $memembers = XhpmTaskMember::find([
                'columns' => 'iUserId',
                'conditions' => 'bDelete=0 AND iTaskId = :iTaskId: ',
                'bind' => array('iTaskId' => $iTaskId),
            ])->toArray();
            $memberIds = [];
            foreach ($memembers as $memember) {
                $memberIds[] = $memember['iUserId'];
            }
            $taskInfo = $taskInfo ? $taskInfo->toArray() : [];
            $taskInfo['executorId'] = $executorId ? $executorId->iUserId : '';
            $taskInfo['memberIds'] = $memberIds;
            return $this->sendJsonResponse($taskInfo);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取任务信息失败', $exception->getMessage());
        }
    }

    /**
     * 开始或者完成任务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180420
     * modify by zqk 20180510
     */
    public function changeStatusAction()
    {
        if (!Power::exist('Bpm_Project_Task_Edit')) {
            return $this->sendErrorResponse(500, '权限不足');
        }
        $userId = Main::getLoginUserInfo('userId');
        $iTaskId = $this->request->getPost('iTaskId', 'int');
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $status = $this->request->getPost('iTaskStatus', 'int');
        $dRealTaskTime = $this->request->getPost('dRealTaskTime');
        try {
            $this->db->begin(); //开启事务
            if ($iProjectId) {
                $ifPower = $this->checkIfNewTask($iProjectId, 0, 0);
                if (!$ifPower) {
                    return $this->sendErrorResponse(400, '参数错误');
                }
            }
            $task = XhpmProjectTask::findFirst([
                'conditions' => "iTaskId = $iTaskId AND bDelete = 0"
            ]);
            $iParentId = $task->iParentId;
            if ($iParentId) {
                $fatherTask = XhpmProjectTask::findFirst([
                    'columns' => 'iTaskStatus',
                    'conditions' => "bDelete = 0 AND iTaskId = $iParentId"
                ]);
                if (in_array($fatherTask->iTaskStatus, [3, 4])) {
                    return $this->sendErrorResponse(500, '父级任务已完成/已关闭');
                }
            }
            $taskstatus = self::$task_status;
            $creator = XhpmTaskMember::findFirst([
                'conditions' => "iUserId = $userId AND (bIfCreator = 1 or bIfExecutor = 1 or bCharge = 1) AND iTaskId = $iTaskId",
            ]);
            if (!$iTaskId || !in_array($status, [2, 3, 4])) {
                return $this->sendErrorResponse(500, '操作失败', '参数错误');
            }
            if (!$task || (!$creator && !User::isAdmin())) {
                return $this->sendErrorResponse(500, '操作失败', '无操作该任务权限');
            }
            $oldStatus = $task->iTaskStatus;
            if ($oldStatus == $status) {
                return $this->sendErrorResponse(500, '操作失败', '任务' . $taskstatus[$status]);
            }
            $task->iTaskStatus = $status;
            $date = date('Y-m-d H:i:s', time());
            if ($status == 3) {
                $unCondition = "bDelete=0 AND iTaskStatus != 3 AND iTaskStatus != 4 AND iParentId = :iParentId:";
                $unParameter = array(
                    'columns' => 'iTaskId',
                    'conditions' => $unCondition,
                    'bind' => array('iParentId' => $iTaskId),
                );
                $unFnum = XhpmProjectTask::count($unParameter);
                if ($unFnum) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '操作失败', '还有子任务未完成');
                }
                $task->iProcess = 100;
                $task->tFinishedAt = $date;
                $task->dRealTaskTime = $dRealTaskTime;
            } elseif ($status == 2) {
                $task->iProcess = 0;
                $task->dRealTaskTime = 0;
                $task->tStartedAt = $date;
            }
            $re = $task->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败', '修改任务状态失败');
            }
            //任务关闭或者完成时,若父级任务存在则修改父级任务进度
            if ($iParentId) {
                $pre = $this->modifyParentTask($iParentId);
                if (!$pre) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '操作失败', '父级进度修改失败');
                }
            }
            //
            $userName = Main::getLoginUserInfo('userName');
            $content = '';
            switch ($status) {
                case 2:
                    $content = $userName . '开启任务' . $task->sTaskName;
                    break;
                case 3:
                    $content = $userName . '完成任务' . $task->sTaskName;
                    break;
                case 4:
                    $content = $userName . '关闭任务' . $task->sTaskName;
                    break;
            }
            $taskLog = new XhpmTaskLog();
            $taskLog->iTaskId = $task->iTaskId;
            $taskLog->sContent = $content;
            $r = $taskLog->save();
            if (!$r) {
                $this->db->rollback();
                return $this->sendErrorResponse(400, '操作失败', '创建任务日志失败');
            }
            //项目统计表start
            $prore = $this->modifyProjectCount($task->iProjectId, 2, $status, $oldStatus);
            if (!$prore) {
                return $this->sendErrorResponse(400, '操作失败', '项目统计失败');
            }
            //项目统计end
            //日程联动
            $schedule = XhpmSchedule::findFirst([
                'conditions' => "iTaskId = $iTaskId AND bDelete = 0",
            ]);
            if ($schedule) {
                $schedule->iScheduleStatus = $status;
                $result = $schedule->save();
                if (!$result) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '操作失败', '对应问题跟踪状态变更失败');
                }
            }
            if ($status == 4) {
                $result = $this->closeChildrenTasks($iTaskId);
                if (!$result) {
                    $this->db->rollback();
                    return $this->sendErrorResponse('500', '关闭子任务失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 获取任务树结构信息  id ,text easyui
     * @return string
     * created by zqk 2018/4/16
     */
    public function getTasksAction()
    {
        $iProjectId = $this->request->get('projectId', 'int', 0);
        $iSelectProjectId = $this->request->get('selectProjectId', 'int', 0);
        $pId = $iSelectProjectId ? $iSelectProjectId : $iProjectId;
        $newArray[0]['id'] = 0;
        $newArray[0]['text'] = '父级任务';
        $newArray[0]['iconCls'] = 'fa fa-group';
        $newArray[0]['children'] = $this->getChildrenTask(0, $pId);
        return $this->sendJsonResponse($newArray);
    }

    /**
     * 获取子项目结构
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180409
     */
    public function getChildrenTask($iParentid, $iProjectId)
    {
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:iParentId: AND iProjectId=:iProjectId: ",
            'bind' => array('iParentId' => $iParentid, 'bDelete' => 0, 'iProjectId' => $iProjectId),
        );
        $objs = XhpmProjectTask::find($parameters);
        if ($objs == null) {
            return [];
        }
        $array = $objs->toArray();
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key]['id'] = $value['iTaskId'];
            $newArray[$key]['text'] = $value['sTaskName'];
            $newArray[$key]['iconCls'] = 'fa fa-group';
            $newArray[$key]['children'] = $this->getChildrenTask($value['iTaskId'], $iProjectId);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        return $newArray;
    }

    /**
     * 检查项目id是否合法权限 判断项目ID是否合法(跳转验证)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180531
     */
    private function checkTaskListPower($projectId)
    {
        if (!$projectId) {
            return false;
        }
        $condition = "bDelete = 0 AND iProjectId = $projectId AND iParentPid=0 AND iProjectGrade=1";   //项目级别 并且是项目成员
        $pids = $this->getProjectIds();
        if (!$pids && !User::isAdmin()) {
            return false;
        }
        $projectObj = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where($condition);
            if (!User::isAdmin()) {
                $projectObj ->inWhere("iProjectId", $pids);
            }
        $num = $projectObj->getQuery()->execute()->count();
        if (!$num) {
            return false;
        }
        return true;
    }

    /**
     * 项目列表双击跳转到任务验证
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180601
     */
    public function checkTaskListPowerAction()
    {
        $iProjectId = $this->request->get('iProjectId', 'int');
        $re = $this->checkTaskListPower($iProjectId);
        if ($re) {
            return $this->sendSuccessResponse('验证成功');
        } else {
            return $this->sendErrorResponse(500, '参数错误');
        }
    }

    /**
     * 验证新建task权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180531
     */
    private function checkIfNewTask($iProjectId, $selectProjectId, $selectProjectGrade)
    {
        $re = $this->checkTaskListPower($iProjectId);
        if (!$re) {
            return false;
        }
        if ($selectProjectGrade && $selectProjectId) {
            //版本
            if ($selectProjectGrade == 2) {
                $visionObj = XhpmProject::findFirst([
                    'conditions' => "bDelete = 0 AND iProjectGrade = 2 AND iProjectId = $selectProjectId",
                ]);
                if ($visionObj) {
                    if ($visionObj->iParentPid != $iProjectId) {
                        return false;
                    }
                } else {
                    return false;
                }
            } elseif ($selectProjectGrade == 3) {
                $moudleObj = XhpmProject::findFirst([
                    'conditions' => "bDelete = 0 AND iProjectGrade = 3 AND iProjectId = $selectProjectId",
                ]);
                if ($moudleObj) {
                    $visionId = $moudleObj->iParentPid;
                    $visionObj = XhpmProject::findFirst([
                        'conditions' => "bDelete = 0 AND iProjectGrade = 2 AND iProjectId = $visionId",
                    ]);
                    if ($visionObj) {
                        if ($visionObj->iParentPid != $iProjectId) {
                            return false;
                        }
                    } else {
                        if ($moudleObj->iParentPid != $iProjectId) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            }
        } elseif (($selectProjectGrade && !$selectProjectId) || (!$selectProjectGrade && $selectProjectId)) {
            return false;
        }
        return true;
    }

    /**
     * 新建任务时弹窗前验证权限包括项目id验证  以及选中版本或者模块是否属于模块的验证
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180601
     */
    public function checkIfNewTaskAction()
    {
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $selectProjectGrade = $this->request->getPost('selectProjectGrade', 'int');
        $selectProjectId = $this->request->getPost('selectProjectId', 'int');
        $re = $this->checkIfNewTask($iProjectId, $selectProjectId, $selectProjectGrade);

        if ($re) {
            return $this->sendSuccessResponse('验证成功');
        } else {
            return $this->sendErrorResponse(400, '参数错误');
        }
    }

    /**
     * 新建任务 变更任务状态 删除任务修改父级进度及状态
     *
     * @param $parentId
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180822
     */
    private function modifyParentTask($parentId)
    {
        $fatherTask = XhpmProjectTask::findFirst([
            'conditions' => "bDelete = 0 AND iTaskId = $parentId"
        ]);
        $finCondition = "bDelete=0 AND iParentId = :iParentId: AND iTaskStatus = 3";
        $finParameter = array(
            'columns' => 'iTaskId',
            'conditions' => $finCondition,
            'bind' => array('iParentId' => $parentId),
        );
        $finNum = XhpmProjectTask::count($finParameter);
        $sumCondition = "bDelete=0 AND iTaskStatus != 4 AND iParentId = :iParentId:";
        $sumParameter = array(
            'columns' => 'iTaskId',
            'conditions' => $sumCondition,
            'bind' => array('iParentId' => $parentId),
        );
        $sumfNum = XhpmProjectTask::count($sumParameter);
        $process = 0;
        if ($sumfNum) {
            $floatNum = intval($finNum) / $sumfNum;
            $process = intval(sprintf("%.2f", $floatNum) * 100);
        }
        $fatherTask->iProcess = $process;
        $fare = $fatherTask->save();
        if (!$fare) {
            return false;
        }
        return true;
    }

    /**
     * 编辑项目统计表
     *
     * @param $projectId
     * @param $type
     * @param int $status
     * @param int $oldStatus
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180823
     */
    private function modifyProjectCount($projectId, $type, $status = 0, $oldStatus = 0)
    {
        $project = XhpmProject::findFirst([
            'columns' => 'iProjectGrade,iParentPid',
            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
            'bind' => array('iProjectId' => $projectId),
        ]);
        $fatherProject = XhpmProject::findFirst([
            'columns' => 'iProjectId',
            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
            'bind' => array('iProjectId' => $project->iParentPid),
        ]);

        $grade = $project->iProjectGrade;
        $projectCount = XhpmProjectCount::findFirst(
            [
                'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                'bind' => array('iProjectId' => $projectId),
                'for_update' => true
            ]
        );
        if ($type == 1) {  //新增
            $resu = 0;
            if ($grade == 1) {
                $projectCount->iSumTaskNum = $projectCount->iSumTaskNum + 1;
                $resu = $projectCount->save();
            } elseif ($grade == 2) {
                if (!$fatherProject) {
                    return false;
                }
                $projectCount->iSumTaskNum = $projectCount->iSumTaskNum + 1;
                $resu = $projectCount->save();
            } elseif ($grade == 3) {
                if (!$fatherProject) {
                    return false;
                }
                $fprojectCount = XhpmProjectCount::findFirst(
                    [
                        'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                        'bind' => array('iProjectId' => $fatherProject->iProjectId),
                        'for_update' => true
                    ]
                );
                $fprojectCount->iSumTaskNum = $fprojectCount->iSumTaskNum + 1;
                $resu1 = $fprojectCount->save();
                if ($resu1) {
                    $projectCount->iSumTaskNum = $projectCount->iSumTaskNum + 1;
                    $resu = $projectCount->save();
                }
            }
            if (!$resu) {
                return false;
            }
            return true;
        } elseif ($type == 2) {  //变更状态
            $finishTaskNum = $projectCount->iFinishedTaskNum;
            $sumTaskNum = $projectCount->iSumTaskNum;
            if (in_array($oldStatus, [1, 2]) && in_array($status, [3, 4])) {
                if ($grade == 1) {
                    $status == 3 ? $projectCount->iFinishedTaskNum = $finishTaskNum + 1
                        : $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 2) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $status == 3 ? $projectCount->iFinishedTaskNum = $finishTaskNum + 1
                        : $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 3) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $fprojectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $fatherProject->iProjectId),
                            'for_update' => true
                        ]
                    );
                    $fSumTaskNum = $fprojectCount->iSumTaskNum;
                    $fFinishTaskNum = $fprojectCount->iFinishedTaskNum;
                    $status == 3 ? $fprojectCount->iFinishedTaskNum = $fFinishTaskNum + 1
                        : $fprojectCount->iSumTaskNum = $fSumTaskNum - 1;
                    $res1 = $fprojectCount->save();
                    if ($res1) {
                        $status == 3 ? $projectCount->iFinishedTaskNum = $finishTaskNum + 1
                            : $projectCount->iSumTaskNum = $sumTaskNum - 1;
                        $res = $projectCount->save();
                        if (!$res) {
                            return false;
                        }
                    }
                }
            } elseif ($oldStatus == 3 && in_array($status, [2, 4])) {
                if ($grade == 1) {
                    if ($status == 2) {//完成转开始
                        $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                    } else {//完成转关闭
                        $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                        $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    }
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 2) {
                    if (!$fatherProject) {
                        return false;
                    }
                    if ($status == 2) {//完成转开始
                        $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                    } else {//完成转关闭
                        $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                        $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    }
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 3) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $fprojectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $fatherProject->iProjectId),
                            'for_update' => true
                        ]
                    );
                    $fSumTaskNum = $fprojectCount->iSumTaskNum;
                    $fFinishTaskNum = $fprojectCount->iFinishedTaskNum;
                    if ($status == 2) {//完成转开始
                        $fprojectCount->iFinishedTaskNum = $fFinishTaskNum - 1;
                    } else {//完成转关闭
                        $fprojectCount->iFinishedTaskNum = $fFinishTaskNum - 1;
                        $fprojectCount->iSumTaskNum = $fSumTaskNum - 1;
                    }
                    $res1 = $fprojectCount->save();
                    if ($res1) {
                        if ($status == 2) {//完成转开始
                            $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                        } else {//完成转关闭
                            $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                            $projectCount->iSumTaskNum = $sumTaskNum - 1;
                        }
                        $res = $projectCount->save();
                        if (!$res) {
                            return false;
                        }
                    }
                }
            } elseif ($oldStatus == 4 && in_array($status, [2, 3])) {
                if ($grade == 1) {
                    if ($status == 2) {//关闭转开始
                        $projectCount->iSumTaskNum = $sumTaskNum + 1;
                    } else {//关闭转完成
                        $projectCount->iFinishedTaskNum = $finishTaskNum + 1;
                        $projectCount->iSumTaskNum = $sumTaskNum + 1;
                    }
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 2) {
                    if (!$fatherProject) {
                        return false;
                    }
                    if ($status == 2) {//关闭转开始
                        $projectCount->iSumTaskNum = $sumTaskNum + 1;
                    } else {//关闭转完成
                        $projectCount->iFinishedTaskNum = $finishTaskNum + 1;
                        $projectCount->iSumTaskNum = $sumTaskNum + 1;
                    }
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 3) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $fprojectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $fatherProject->iProjectId),
                            'for_update' => true
                        ]
                    );
                    $fSumTaskNum = $fprojectCount->iSumTaskNum;
                    $fFinishTaskNum = $fprojectCount->iFinishedTaskNum;
                    if ($status == 2) {//关闭转开始
                        $fprojectCount->iSumTaskNum = $fSumTaskNum + 1;
                    } else {//关闭转完成
                        $fprojectCount->iFinishedTaskNum = $fFinishTaskNum + 1;
                        $fprojectCount->iSumTaskNum = $fSumTaskNum + 1;
                    }
                    $res1 = $fprojectCount->save();
                    if ($res1) {
                        if ($status == 2) {//关闭转开始
                            $projectCount->iSumTaskNum = $sumTaskNum + 1;
                        } else {//关闭转完成
                            $projectCount->iSumTaskNum = $sumTaskNum + 1;
                            $projectCount->iFinishedTaskNum = $finishTaskNum + 1;
                        }
                        $res = $projectCount->save();
                        if (!$res) {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
            }
            return true;
        } elseif ($type == 3) {  //删除
            $grade = $project->iProjectGrade;
            $finishTaskNum = $projectCount->iFinishedTaskNum;
            $sumTaskNum = $projectCount->iSumTaskNum;
            if (in_array($oldStatus, [1, 2])) {
                if ($grade == 1) {
                    $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 2) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 3) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $fprojectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $fatherProject->iProjectId),
                            'for_update' => true
                        ]
                    );
                    $fSumTaskNum = $fprojectCount->iSumTaskNum;
                    $fprojectCount->iSumTaskNum = $fSumTaskNum - 1;
                    $res1 = $fprojectCount->save();
                    if ($res1) {
                        $projectCount->iSumTaskNum = $sumTaskNum - 1;
                        $res = $projectCount->save();
                        if (!$res) {
                            return false;
                        }
                    }
                }
            } elseif ($oldStatus == 3) {
                if ($grade == 1) {
                    $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                    $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 2) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                    $projectCount->iSumTaskNum = $sumTaskNum - 1;
                    $res = $projectCount->save();
                    if (!$res) {
                        return false;
                    }
                } elseif ($grade == 3) {
                    if (!$fatherProject) {
                        return false;
                    }
                    $fprojectCount = XhpmProjectCount::findFirst(
                        [
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $fatherProject->iProjectId),
                            'for_update' => true
                        ]
                    );
                    $fSumTaskNum = $fprojectCount->iSumTaskNum;
                    $fFinishTaskNum = $fprojectCount->iFinishedTaskNum;
                    $fprojectCount->iFinishedTaskNum = $fFinishTaskNum - 1;
                    $fprojectCount->iSumTaskNum = $fSumTaskNum - 1;
                    $res1 = $fprojectCount->save();
                    if ($res1) {
                        $projectCount->iFinishedTaskNum = $finishTaskNum - 1;
                        $projectCount->iSumTaskNum = $sumTaskNum - 1;
                        $res = $projectCount->save();
                        if (!$res) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
    }

    /**
     * 删除任务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180718
     */
    public function delTaskByIdAction()
    {
        if (!Power::exist('Bpm_Project_Task_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除任务权限');
        }
        $userName = Main::getLoginUserInfo('userName');
        $userId = Main::getLoginUserInfo('userId');
        $iTaskId = $this->request->getPost('iTaskId', 'int');
        try {
            $this->db->begin();
            $taskObj = XhpmProjectTask::findFirst([
                'conditions' => "bDelete = 0 AND iTaskId = $iTaskId"
            ]);
            if (!$taskObj) {
                return $this->sendErrorResponse(400, '该任务不存在');
            }
            if ($taskObj->bChecked == 1) {
                return $this->sendErrorResponse(400, '任务已审核');
            }
            $iParentId = $taskObj->iParentId;
            if ($iParentId) {
                $fatherTask = XhpmProjectTask::findFirst([
                    'columns' => 'iTaskStatus',
                    'conditions' => "bDelete = 0 AND iTaskId = $iParentId"
                ]);
                if (in_array($fatherTask->iTaskStatus, [3, 4])) {
                    return $this->sendErrorResponse(500, '父级任务已完成/已关闭');
                }
            }
            $creator = XhpmTaskMember::findFirst([
                'conditions' => "iUserId = $userId AND (bIfCreator = 1 OR bIfExecutor = 1) AND iTaskId = $iTaskId",
            ]);
            if (!User::isAdmin() && !$creator) {
                return $this->sendErrorResponse(500, '删除失败', '只有任务创建人/执行人才能删除任务');
            }
            $taskObj->bDelete = 1;
            $re = $taskObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            //任务删除时,若父级任务存在则修改父级任务进度
            if ($iParentId) {
                $pre = $this->modifyParentTask($iParentId);
                if (!$pre) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '操作失败', '父级进度修改失败');
                }
            }
            //项目统计表start
            $oldStatus = $taskObj->iTaskStatus;
            $pId = $taskObj->iProjectId;
            $pre = $this->modifyProjectCount($pId, 3, 0, $oldStatus);
            if (!$pre) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败', '项目统计失败');
            }
            //日程联动
            $schedule = XhpmSchedule::findFirst([
                'conditions' => "iTaskId = $iTaskId AND bDelete = 0",
            ]);
            if ($schedule) {
                $schedule->bDelete = 1;
                $result = $schedule->save();
                if (!$result) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '操作失败', '对应问题跟踪状态变更失败');
                }
            }
            //删除子任务
            $result = $this->delChildrenTasks($iTaskId);
            if (!$result) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除子任务失败');
            }
            $content = $userName . '删除任务' . $taskObj->sTaskName;
            $Log = new XhpmTaskLog();
            $Log->sContent = $content;
            $Log->iTaskId = $iTaskId;
            $res = $Log->save();
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 删除子任务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180823
     */
    private function delChildrenTasks($id)
    {
        $tasks = XhpmProjectTask::find([
            'conditions' => "bDelete = 0 AND iParentId = $id"
        ]);
        foreach ($tasks as $task) {
            $task->bDelete = 1;
            $re = $task->save();
            if (!$re) {
                return false;
            }
            //项目统计表start
            $oldStatus = $task->iTaskStatus;
            $id = $task->iProjectId;
            $pre = $this->modifyProjectCount($id, 3, 0, $oldStatus);
            if (!$pre) {
                return false;
            }
            //日程联动
            $schedule = XhpmSchedule::findFirst([
                'conditions' => "iTaskId = $task->iTaskId AND bDelete = 0",
            ]);
            if ($schedule) {
                $schedule->bDelete = 1;
                $result = $schedule->save();
                if (!$result) {
                    return false;
                }
            }
            $res = $this->delChildrenTasks($task->iTaskId);
            if (!$res) {
                return false;
            }
        }
        return true;
    }

    /**
     * 关闭子任务
     *
     * @param $id
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180823
     */
    private function closeChildrenTasks($id)
    {
        $tasks = XhpmProjectTask::find([
            'conditions' => "bDelete = 0 AND iParentId = $id"
        ]);
        foreach ($tasks as $task) {
            $oldStatus = $task->iTaskStatus;
            $task->iTaskStatus = 4;
            $re = $task->save();
            if (!$re) {
                return false;
            }
            //项目统计表start
            $pid = $task->iProjectId;
            $pre = $this->modifyProjectCount($pid, 2, 4, $oldStatus);
            if (!$pre) {
                return false;
            }
            //日程联动
            $schedule = XhpmSchedule::findFirst([
                'conditions' => "iTaskId = $task->iTaskId AND bDelete = 0",
            ]);
            if ($schedule) {
                $schedule->iScheduleStatus = 4;
                $result = $schedule->save();
                if (!$result) {
                    return false;
                }
            }
            $res = $this->closeChildrenTasks($task->iTaskId);
            if (!$res) {
                return false;
            }
        }
        return true;
    }

    /**
     * publicTasks 列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180806
     */
    public function publicTasksAction()
    {
        if (!Power::exist('Bpm_Project_Task_Edit')) {
            return $this->sendViewError('权限不足');
        }
        $iTaskId = $this->request->getQuery('iTaskId', 'int');//项目Id
        if (!$iTaskId) {
            return $this->sendViewError('参数错误');
        }
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/task/publicTasks.js');
        $this->view->setVars([
            'iTaskId' => $iTaskId,
        ]);
        $this->view->pick('task/publicTasks');
    }

    /**
     * 获取getPublicTasks
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180806
     */
    public function getPublicTasksAction()
    {
        if (!Power::exist('Bpm_Project_Task_Edit')) {
            return $this->sendErrorResponse(500, '权限不足');
        }
        $iTaskId = $this->request->getPost('iTaskId', 'int', 0);
        if (!$iTaskId) {
            return $this->sendErrorResponse(500, '参数错误');
        }
        $sTaskName = $this->request->getPost('sTaskName', 'string');
        $conditions = 't.bDelete = 0 AND t.bPublic = 1 AND t.iTaskId != ' . $iTaskId;
        $conditions .= $sTaskName ? " AND t.sTaskName Like '%$sTaskName%'" : '';
        //为传递类型
        $builder = $this->modelsManager->createBuilder()
            ->columns("t.iTaskId,t.sTaskName,t.sTaskContent,u.sStaffName")
            ->addFrom('Admin\Models\pm\XhpmProjectTask', 't')
            ->leftjoin('Admin\Models\pm\XhpmTaskMember', 'm.iTaskId=t.iTaskId AND m.bIfExecutor =1 AND m.bDelete = 0', 'm')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
            ->where($conditions);
        $datas = Main::runBuilderPaginator($builder, true);
        return $this->sendJsonResponse($datas);
    }

    /**
     * getCheckedTasks
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180806
     */
    public function getCheckedTasksAction()
    {
        $iTaskId = $this->request->getPost('iTaskId', 'int');
        $conditions = "bDelete = 0 AND iTaskId = $iTaskId";
        //为传递类型
        $task = XhpmProjectTask::findFirst([
            'columns' => 'sRelatedId',
            'conditions' => $conditions,
        ]);
        if (!$task) {
            return $this->sendJsonResponse([]);
        }
        $taskIds = explode(',', $task->sRelatedId);
        return $this->sendJsonResponse($taskIds);
    }

    /**
     * 添加关联任务
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180806
     */
    public function addRelatedTasksAction()
    {
        $iTaskId = $this->request->getPost('iTaskId', 'int');
        $iTaskIds = $this->request->getPost('iTaskIds');
        $userId = Main::getLoginUserInfo('userId');
        $userName = Main::getLoginUserInfo('userName');
        try {
            $this->db->begin();  //开启事务
            if (!Power::exist('Bpm_Project_Task_Edit')) {
                return $this->sendErrorResponse(500, '权限不足', '无任务关联权限');
            }
            $task = XhpmProjectTask::findFirst([
                'conditions' => "iTaskId = $iTaskId AND bDelete = 0"
            ]);
            $creator = XhpmTaskMember::findFirst([
                'conditions' => "iUserId = $userId AND (bIfCreator = 1 or bIfExecutor = 1 or bCharge = 1)  AND iTaskId = $iTaskId",
            ]);
            if (!$task || (!$creator && !User::isAdmin())) {
                return $this->sendErrorResponse(500, '操作失败', '无操作该任务权限');
            }
            $iTIds = implode(',', $iTaskIds);
            $task->sRelatedId = $iTIds;
            $result = $task->save();
            if (!$result) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败');
            }
            //写入项目日志
            $sContent = $userName . '为' . $task->sTaskName . '添加关联任务';
            $taskLog = new XhpmTaskLog();
            $taskLog->iTaskId = $task->iTaskId;
            $taskLog->sContent = $sContent;
            $r = $taskLog->save();
            if (!$r) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

###################################################  项 目 相 关  ######################################################

    /**
     * 获取版本列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180412
     */
    public function getVisionsAction()
    {
        try {
            if (!Power::exist('Bpm_Project_Version')) {
                return $this->sendErrorResponse(500, '无版本权限');
            }
            $iProjectId = $this->request->getQuery('iProjectId', 'int');
            $re = $this->checkTaskListPower($iProjectId);
            if (!$re) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            $pids = $this->getProjectIds();
            if (!$pids && !User::isAdmin()) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            $status = $this->request->getPost('status', 'int'); //根据项目状态太筛选
            $projectName = $this->request->getPost('projectName', 'string'); //根据项目状态太筛选
            $condition = "p.bDelete=0 AND p.iParentPid=$iProjectId AND iProjectGrade=2";
            $condition .= $status ? " AND p.iProjectStatus = $status" : '';
            $condition .= $projectName ? " AND p.sProjectName  LIKE '%$projectName%'" : '';
            $builder = $this->modelsManager->createBuilder()
                ->columns("c.iSumTaskNum,c.iFinishedTaskNum,p.iProjectId,p.iProjectGrade,p.sProjectName,p.sProjectIntroduce,p.iProjectType,p.iParentPid,p.sProjectVersion,p.iProjectStatus,p.tCreateDate,p.tLastModifyDate")
                ->addFrom('Admin\Models\pm\XhpmProject', 'p')
                ->leftjoin('Admin\Models\pm\XhpmProjectCount', 'p.iProjectId = c.iProjectId', 'c')
                ->where($condition);
            if(!User::isAdmin()) {
                $builder ->inWhere("p.iProjectId", $pids);//暂时限制后续大概率干掉
            }
            $builder->orderBy("p.iProjectId desc");
            $data = Main::runBuilderPaginator($builder, true);
            foreach ($data['rows'] as $key => $value) {
                $data['rows'][$key]['sProjectName'] = $data['rows'][$key]['sProjectVersion'];
                if ($data['rows'][$key]['iSumTaskNum']) {
                    $floatNum = intval($data['rows'][$key]['iFinishedTaskNum']) / $data['rows'][$key]['iSumTaskNum'];
                    $process = intval(sprintf("%.2f", $floatNum) * 100);
                    $data['rows'][$key]['iProcess'] = $process;
                } else {
                    $data['rows'][$key]['iProcess'] = 0;
                }
                $prostatus = $data['rows'][$key]['iProjectStatus'];
                switch ($prostatus) {
                    case 1:
                        $data['rows'][$key]['iconCls'] = 'fa fa-file-text';
                        break;
                    case 2:
                        $data['rows'][$key]['iconCls'] = 'fa fa-play';
                        break;
                    case 3:
                        $data['rows'][$key]['iconCls'] = 'fa fa-plus-square';
                        break;
                    case 4:
                        $data['rows'][$key]['iconCls'] = 'fa fa-forward';
                        break;
                    case 5:
                        $data['rows'][$key]['iconCls'] = 'fa fa-check';
                        break;
                    case 6:
                        $data['rows'][$key]['iconCls'] = 'fa fa-pause';
                        break;
                }
                $condition1 = "bDelete=0 AND iParentPid=:iParentPid:";
                $parameters = array(
                    'columns' => 'iProjectId',
                    'conditions' => $condition1,
                    'bind' => array('iParentPid' => $value['iProjectId']),
                );
                $objs = XhpmProject::find($parameters)->toArray();
                $data['rows'][$key]['state'] = empty($objs) ? '' : "closed";
                $data['rows'][$key]['children'] = $this->getProjectChildren($value['iProjectId'], $pids);
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());

        }
    }

    /**
     * 获取项目子项目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180523
     */
    private function getProjectChildren($id, $pids)
    {
        $condition = "p.bDelete=0 AND p.iParentPid=:iParentPid:";
        $condition1 = "bDelete=0 AND iParentPid=:iParentPid:";
        $param = array('iParentPid' => $id);
        $data = $this->modelsManager->createBuilder()
            ->columns("c.iSumTaskNum,c.iFinishedTaskNum,p.iProjectId,p.iProjectGrade,p.sProjectName,p.sProjectIntroduce,p.iProjectType,p.iParentPid,p.sProjectVersion,p.iProjectStatus,p.tCreateDate,p.tLastModifyDate")
            ->addFrom('Admin\Models\pm\XhpmProject', 'p')
            ->leftjoin('Admin\Models\pm\XhpmProjectCount', 'p.iProjectId = c.iProjectId', 'c')
            ->where($condition, $param)
            ->inWhere('p.iProjectId', $pids)
            ->orderBy("p.iProjectId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        $cPid = XhpmProject::findFirst([
            'columns' => 'iProjectId,iProjectStatus',
            'conditions' => "iProjectId = $id AND bDelete = 0",
        ]);
        foreach ($data as $k => $v) {
            if ($data[$k]['iSumTaskNum']) {
                $floatNum = intval($data[$k]['iFinishedTaskNum']) / $data[$k]['iSumTaskNum'];
                $process = intval(sprintf("%.2f", $floatNum) * 100);
                $data[$k]['iProcess'] = $process;
            } else {
                $data[$k]['iProcess'] = 0;
            }
            $pstatus = $data[$k]['iProjectStatus'];
            if ($data[$k]['iProjectGrade'] == 2) {
                $data[$k]['iProjectStatus'] = $pstatus ? $pstatus : 0;
            } else {
                $data[$k]['iProjectStatus'] = $cPid->iProjectStatus ? $cPid->iProjectStatus : 0;
                $prostatus = $cPid->iProjectStatus;
                switch ($prostatus) {
                    case 1:
                        $data[$k]['iconCls'] = 'fa fa-file-text';
                        break;
                    case 2:
                        $data[$k]['iconCls'] = 'fa fa-play';
                        break;
                    case 3:
                        $data[$k]['iconCls'] = 'fa fa-plus-square';
                        break;
                    case 4:
                        $data[$k]['iconCls'] = 'fa fa-forward';
                        break;
                    case 5:
                        $data[$k]['iconCls'] = 'fa fa-check';
                        break;
                    case 6:
                        $data[$k]['iconCls'] = 'fa fa-pause';
                        break;
                }
            }
            $data[$k]['sProjectName'] = $data[$k]['iProjectGrade'] == 2 ? $data[$k]['sProjectVersion']
                : $data[$k]['sProjectName'];
            $data[$k]['children'] = $this->getProjectChildren($v['iProjectId'], $pids);
            $parameters = array(
                'alis' => 'p',
                'columns' => 'iProjectId',
                'conditions' => $condition1,
                'bind' => array('iParentPid' => $v['iProjectId']),
            );
            $objs = XhpmProject::find($parameters)->toArray();
            if (!empty($objs)) {
                $data[$k]['state'] = "closed";
            }
        }
        return $data;
    }

    /**
     * 获取可以查看的项目ids
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180601
     */
    private function getProjectIds()
    {
        $deps = User::getextrapower('dep', 'project');  //获取扩展部门权限
        $uids = [];
        if ($deps) {
            $deps = implode(",%' OR  sDepIds like '%,", $deps);
            $conditions = 'bDelete = 0';
            $conditions .= " AND (sDepIds like '%," . $deps . ",%' ) ";
            $users = $this->modelsManager->createBuilder()
                ->columns("iUserId")
                ->From('Admin\Models\hrm\XhhrmStaff')
                ->where($conditions)
                ->getQuery()
                ->execute()
                ->toArray();
            foreach ($users as $k => $user) {
                $uids[] = $user['iUserId'];
            }
        }
        $userId = Main::getLoginUserInfo('userId');
        array_push($uids, $userId);
        $uids = array_unique($uids);
        $projectIds = $this->modelsManager->createBuilder()
            ->columns("iProjectId")
            ->addFrom('Admin\Models\pm\XhpmProjectMember')
            ->where("bDelete = 0")
            ->inwhere('iUserId', $uids)
            ->groupBy('iProjectId')
            ->getQuery()
            ->execute()
            ->toArray();
        $pids = [];
        foreach ($projectIds as $projectId) {
            $pids[] = $projectId['iProjectId'];
        }
        return $pids;
    }
}

